package com.hxd.otc.module.home.fragment;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.hxd.otc.MainActivity;
import com.hxd.otc.R;
import com.hxd.otc.base.LazyFragment;
import com.hxd.otc.common.UserHelper;
import com.hxd.otc.module.convenience.activity.ConvenienceActivity;
import com.hxd.otc.module.convenience.adapter.ConvenienceBannerAdapter;
import com.hxd.otc.module.convenience.bean.ConvenienceBannerBean;
import com.hxd.otc.module.home.activity.MessageActivity;
import com.hxd.otc.module.home.contract.HomePageContract;
import com.hxd.otc.module.home.presenter.HomePagePresenter;
import com.hxd.otc.module.login.activity.LoginActivity;
import com.hxd.otc.module.my.activity.AfficheActivity;
import com.hxd.otc.module.my.activity.ApplyActivity;
import com.hxd.otc.module.my.activity.ContactCustomerActivity;
import com.hxd.otc.module.my.activity.CooperativeMerchantAccessActivity;
import com.hxd.otc.module.my.activity.ExchangeActivity;
import com.hxd.otc.module.my.activity.ShareThePromotionActivity;
import com.hxd.otc.module.my.activity.VIPServiceActivity;
import com.hxd.otc.module.my.activity.WebViewActivity;
import com.hxd.otc.module.my.fragment.FinancialStatementsFragment;
import com.hxd.otc.module.my.fragment.StableCurrencyFragment;
import com.hxd.otc.module.wallet.activity.WalletActivity;
import com.hxd.otc.utils.DataUtils;
import com.hxd.otc.utils.LogUtils;
import com.hxd.otc.utils.StringUtil;
import com.hxd.otc.utils.hyphenate.HyphenateKeFuUtil;
import com.hxd.otc.widget.MyViewpager;
import com.hxd.otc.widget.VerticalTextview;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.chat.ChatManager;
import com.hyphenate.chat.Message;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.Util;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.scwang.smartrefresh.layout.util.DensityUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 作  者 :  zjl
 * 时  间 :  2019/1/8 10:33
 * 描  述 :  ${首页}
 */
public class HomePageFragment extends LazyFragment<HomePagePresenter> implements HomePageContract.IView {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;

    @BindView(R.id.tabLayout)
    TabLayout mTabLayout;

    @BindView(R.id.rollViewPager)
    RollPagerView rollPagerView;

    @BindView(R.id.viewPager)
    MyViewpager mViewPager;

    @BindView(R.id.tv_euc_number)
    TextView tvEucNumber;

    @BindView(R.id.tv_euc_totle_number)
    TextView tvEucTotleNumber;

    @BindView(R.id.vertical_tv)
    VerticalTextview tvVertical;

    @BindView(R.id.iv_customer_service_red)
    ImageView mIvCustomerServiceRed;

    @BindView(R.id.iv_message_red)
    ImageView mIvMessageRed;

    List<Fragment> mFragmentList;

    String[] tabNames;

    String progremme;

    private ConvenienceBannerAdapter mBannerAdapter;

    StableCurrencyFragment stableCurrencyFragment;
    FinancialStatementsFragment financialStatementsFragment;

    @Override
    protected int getLayoutId() {
//        return R.layout.activity_scrolling;
        return R.layout.fragment_home_page;
    }

    @Override
    protected void initData() {
        mRefreshLayout.autoRefresh(0, 10, 1);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void initView() {
        tabNames = getResources().getStringArray(R.array.array_table_currency);

        initRollPagerView();

        addFragment();

        initViewPager();

        tvVertical.setText(12, 5, ContextCompat.getColor(getContext(), R.color.color_EditText_text));//设置属性
        tvVertical.setTextStillTime(3000);//设置停留时长间隔
        tvVertical.setAnimTime(400);//设置进入和退出的时间间隔

        ChatClient.getInstance().chatManager().addMessageListener(messageListener);
    }

    // 客服 在线聊天消息监听
    private ChatManager.MessageListener messageListener = new ChatManager.MessageListener() {

        @Override
        public void onMessage(final List<Message> messages) {
            //收到普通消息
            if (mIvCustomerServiceRed == null) return;
            mIvCustomerServiceRed.post(new Runnable() {
                @Override
                public void run() {
                    updateCustomerServiceRedPosition();
                }
            });
        }

        @Override
        public void onCmdMessage(List<Message> msgs) {
            //收到命令消息，命令消息不存数据库，一般用来作为系统通知，例如留言评论更新，
            //会话被客服接入，被转接，被关闭提醒
        }

        @Override
        public void onMessageStatusUpdate() {
            //消息的状态修改，一般可以用来刷新列表，显示最新的状态
            if (mIvCustomerServiceRed == null) return;
            mIvCustomerServiceRed.post(new Runnable() {
                @Override
                public void run() {
                    updateCustomerServiceRedPosition();
                }
            });
        }

        @Override
        public void onMessageSent() {
            //发送消息后，会调用，可以在此刷新列表，显示最新的消息
        }
    };

    private void updateCustomerServiceRedPosition() {
        if (isAdded() && getUserVisibleHint()) {
            int unreadMsgsCount = ChatClient.getInstance().chatManager().getUnreadMsgsCount();
            mIvCustomerServiceRed.setVisibility(unreadMsgsCount > 0 ? View.VISIBLE : View.GONE);
        }
    }

    private void initRollPagerView() {

        int width = DataUtils.getScreenWidth(getContext()) - DataUtils.dp2px(getContext(), 30);
        int height = (int) (width * 115f / 345f);
        ViewGroup.LayoutParams layoutParams = rollPagerView.getLayoutParams();
        layoutParams.height = height;
        rollPagerView.setLayoutParams(layoutParams);
        rollPagerView.setAnimationDurtion(1000);

        rollPagerView.setPlayDelay(3000);
        mBannerAdapter = new ConvenienceBannerAdapter(rollPagerView);
        rollPagerView.setAdapter(mBannerAdapter);
        rollPagerView.setHintView(null);
    }

    private void initViewPager() {
        mViewPager.setAdapter(new FragmentStatePagerAdapter(getChildFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return mFragmentList.get(position);
            }

            @Override
            public int getCount() {
                return mFragmentList.size();
            }

            @Override
            public CharSequence getPageTitle(int position) {
                return tabNames[position];
            }
        });
        mViewPager.setOffscreenPageLimit(mFragmentList.size());
        mViewPager.setCurrentItem(0, false);
        mTabLayout.setupWithViewPager(mViewPager, true);

        setupTabIcons();
    }

    private void setupTabIcons() {
        for (int i = 0; i < mFragmentList.size(); i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);//获得每一个tab
            tab.setCustomView(getTabView(i));//给每一个tab设置view
        }
    }

    public View getTabView(int position) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.item_order_tab, null);
        TextView tv_bottom = view.findViewById(R.id.tv_bottom);
        tv_bottom.setText(tabNames[position]);
        tv_bottom.setTextColor(position == 0 ? getResources().getColor(R.color.color_text1) : getResources().getColor(R.color.color_FF95A2AC));
        ImageView ivBotton = view.findViewById(R.id.iv_botton);
        if (position == 0) {
            ivBotton.setVisibility(View.VISIBLE);
            tv_bottom.setTextSize(16);
        } else {
            ivBotton.setVisibility(View.GONE);
            tv_bottom.setTextSize(13);
        }
        return view;
    }

    private void addFragment() {
        mFragmentList = new ArrayList<>();
        stableCurrencyFragment = new StableCurrencyFragment();
        financialStatementsFragment = new FinancialStatementsFragment();
        mFragmentList.add(stableCurrencyFragment);
        mFragmentList.add(financialStatementsFragment);
    }

    int currentPos;

    @Override
    protected void initEvent() {
        mBannerAdapter.setOnBannerClickListener(new ConvenienceBannerAdapter.OnBannerClickListener() {
            @Override
            public void onBannerClick(ConvenienceBannerBean convenienceBannerBean) {
                if (convenienceBannerBean.getBannerType() == 1 && !TextUtils.isEmpty(convenienceBannerBean.getBannerLink()))////1内部链接，2外部链接
                {
                    if (convenienceBannerBean.getBannerLink().equals("10001")) {
                        if (!TextUtils.isEmpty(convenienceBannerBean.getBannerLink())) {
                            mPresenter.bannerUpdate(convenienceBannerBean.getId());
                            Bundle bundle = new Bundle();
                            bundle.putString(WebViewActivity.EXTRA_TITLE, convenienceBannerBean.getBannerName());
                            bundle.putString(WebViewActivity.EXTRA_URL, convenienceBannerBean.getBannerLink());
                            $startActivity(WebViewActivity.class, bundle);
                        }

                    } else if (convenienceBannerBean.getBannerLink().equals("10002")) {
                        $startActivity(VIPServiceActivity.class);
                    }
                } else if (convenienceBannerBean.getBannerType() == 2) {
                    if (!TextUtils.isEmpty(convenienceBannerBean.getBannerLink())) {
                        mPresenter.bannerUpdate(convenienceBannerBean.getId());
                        Bundle bundle = new Bundle();
                        bundle.putString(WebViewActivity.EXTRA_TITLE, convenienceBannerBean.getBannerName());
                        bundle.putString(WebViewActivity.EXTRA_URL, convenienceBannerBean.getBannerLink());
                        $startActivity(WebViewActivity.class, bundle);
                    }
                }

            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPos = position;
                mViewPager.resetHeight(position);
                if (currentPos == 0) {
                    mRefreshLayout.setEnableLoadMore(false);
                } else {
                    mRefreshLayout.setEnableLoadMore(true);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                financialStatementsFragment.loadMoreData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getBannerList();
                MainActivity activity = (MainActivity) getActivity();
                if (activity != null) {
                    activity.getAfficheList();
                }
                if (currentPos == 0) {
                    stableCurrencyFragment.refreshData();
                } else {
                    financialStatementsFragment.refreshData();
                }
            }
        });

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                TextView tabText = tab.getCustomView().findViewById(R.id.tv_bottom);
                tabText.setTextSize(16);
                tabText.setTextColor(getResources().getColor(R.color.color_text1));
                ImageView ivBotton = tab.getCustomView().findViewById(R.id.iv_botton);
                ivBotton.setVisibility(View.VISIBLE);
            }


            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView tabText = tab.getCustomView().findViewById(R.id.tv_bottom);
                tabText.setTextSize(13);
                tabText.setTextColor(getResources().getColor(R.color.color_FF95A2AC));
                ImageView ivBotton = tab.getCustomView().findViewById(R.id.iv_botton);
                ivBotton.setVisibility(View.GONE);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    protected HomePagePresenter createPresenter() {
        return new HomePagePresenter(this);
    }

    @OnClick({R.id.tv_exchange, R.id.tv_wallet, R.id.iv_share, R.id.iv_message})
    public void onClick(View view) {
        if (!UserHelper.isLogin()) {
            $startActivity(LoginActivity.class);
            return;
        }
        switch (view.getId()) {
            case R.id.tv_exchange://兑换
                $startActivity(ExchangeActivity.class);
                break;
            case R.id.tv_wallet://资产
                $startActivity(WalletActivity.class);
                break;
            case R.id.iv_share://推广分享
                $startActivity(ShareThePromotionActivity.class);
                break;
            case R.id.iv_message://消息
                $startActivity(MessageActivity.class);
                mPresenter.updateMessageStatus();
                break;
        }
    }

    @OnClick({R.id.iv_customer_service, R.id.tv_cooperative_merchant, R.id.rl_message,
            R.id.tv_vip, R.id.tv_convenience, R.id.tv_advertiser_apply, R.id.tv_stable_currency_more})
    public void onNotLoginClick(View view) {
        switch (view.getId()) {
            case R.id.iv_customer_service:
                onLineChat();
                break;
            case R.id.tv_cooperative_merchant:
                $startActivity(CooperativeMerchantAccessActivity.class);
                break;
            case R.id.tv_vip:
                $startActivity(VIPServiceActivity.class);
                break;
            case R.id.tv_convenience:
                $startActivity(ConvenienceActivity.class);
                break;
            case R.id.tv_advertiser_apply://广告商认证
                $startActivity(ApplyActivity.class);
                break;
            case R.id.tv_stable_currency_more://查看方案
                jumpToProgremme();
                break;
            case R.id.rl_message://公告滚动条
                $startActivity(AfficheActivity.class);
                break;

        }
    }

    private void jumpToProgremme() {
        if (TextUtils.isEmpty(progremme)) {
            showToast(getString(R.string.no_case));
            return;
        }
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString(WebViewActivity.EXTRA_TITLE, getString(R.string.stable_currency_program));
        bundle.putString(WebViewActivity.EXTRA_URL, progremme);
        bundle.putBoolean(WebViewActivity.EXTRA_IS_PDF, true);
        bundle.putBoolean(WebViewActivity.EXTRA_IS_HELP_CENTER, false);

        intent.putExtras(bundle);
        intent.setClass(getActivity(), WebViewActivity.class);
        startActivity(intent);
    }

    private void onLineChat() {
        if (!ChatClient.getInstance().isLoggedInBefore()) {
            HyphenateKeFuUtil.getInstance().register();
        }
        $startActivity(ContactCustomerActivity.class);
    }


    private void updateBannerPlay() {
        if (mViewPager == null) return;
        if (mBannerAdapter == null) return;
        int realCount = mBannerAdapter.getRealCount();
        if (realCount > 1 && isAdded() && getUserVisibleHint()) {
            rollPagerView.resume();
            rollPagerView.setEnabled(true);
            rollPagerView.setHintView(getHintView());
            rollPagerView.setHintPadding(DensityUtil.dp2px(3), DensityUtil.dp2px(6), DensityUtil.dp2px(3), DensityUtil.dp2px(6));
        } else {
            rollPagerView.pause();
            rollPagerView.setEnabled(false);
            rollPagerView.setHintView(null);
        }
    }

    private ColorPointHintView mHintView;

    public ColorPointHintView getHintView() {
        if (mHintView == null) {
            mHintView = new ColorPointHintView(mContext, mContext.getResources().getColor(android.R.color.white),
                    mContext.getResources().getColor(R.color.color_white_30)) {
                @Override
                public Drawable makeFocusDrawable() {
                    GradientDrawable dot_focus = new GradientDrawable();
                    dot_focus.setColor(mContext.getResources().getColor(android.R.color.white));
                    dot_focus.setCornerRadius(Util.dip2px(getContext(), 2f));
                    dot_focus.setSize(Util.dip2px(getContext(), 4), Util.dip2px(getContext(), 4));
                    return dot_focus;
                }

                @Override
                public Drawable makeNormalDrawable() {
                    GradientDrawable dot_normal = new GradientDrawable();
                    dot_normal.setColor(mContext.getResources().getColor(R.color.color_white_30));
                    dot_normal.setCornerRadius(Util.dip2px(getContext(), 2f));
                    dot_normal.setSize(Util.dip2px(getContext(), 4), Util.dip2px(getContext(), 4));
                    return dot_normal;
                }
            };
        }
        return mHintView;
    }

    @Override
    public void onResume() {
        super.onResume();
        updateBannerPlay();
        updateCustomerServiceRedPosition();
        tvVertical.startAutoScroll();
    }

    @Override
    public void onPause() {
        super.onPause();
        updateBannerPlay();
        tvVertical.stopAutoScroll();
    }

    @Override
    protected void lazyLoad() {
        super.lazyLoad();
        updateBannerPlay();
        if (isAdded() && getUserVisibleHint()) {
            updateCustomerServiceRedPosition();
            mPresenter.getMessageNoReadCount();
        }
    }

    public void setTitleList(ArrayList<String> titleList) {
        if (titleList != null && titleList.size() > 0 && tvVertical != null) {
            tvVertical.setTextList(titleList);
            tvVertical.startAutoScroll();
        }

    }

    public void setProgremme(String progremme, String eucAurrentAmount, String eucAurrentAmountTax) {
        try {
            this.progremme = progremme;
            tvEucNumber.setText(StringUtil.handleZero(eucAurrentAmount));
            tvEucTotleNumber.setText(StringUtil.format2Number(Double.parseDouble(eucAurrentAmountTax)) + getString(R.string.CNY));
        } catch (Exception e) {
            LogUtils.e(e.getMessage());
            tvEucTotleNumber.setText("--");
        }

    }

    @Override
    public void getBannerListSuccess(ArrayList<ConvenienceBannerBean> convenienceBannerBeans) {
        mBannerAdapter.setNewData(convenienceBannerBeans);
        updateBannerPlay();
    }

    @Override
    public void getBannerListFail(String errMessage) {

    }

    @Override
    public void onShowNoMore() {
        mRefreshLayout.finishRefresh();
        mRefreshLayout.finishLoadMore();
    }

    @Override
    public void updateMessageRed(Integer number) {
        mIvMessageRed.setVisibility(number == null || number == 0 ? View.GONE : View.VISIBLE);
    }

    @Override
    public void updateMessageStatusSuccess() {
        mIvMessageRed.setVisibility(View.GONE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ChatClient.getInstance().chatManager().removeMessageListener(messageListener);
    }
}
